package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LemonlaUserPointMapper;
import org.linlinjava.litemall.db.domain.LemonlaSession;
import org.linlinjava.litemall.db.domain.LemonlaUserPoint;
import org.linlinjava.litemall.db.domain.LemonlaUserPointExample;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LemonlaUserPointService {

    @Resource
    private LemonlaUserPointMapper UserPointMapper;

    public LemonlaUserPoint findById(Integer id) {
        LemonlaUserPointExample example = new LemonlaUserPointExample();
        example.or().andIdEqualTo(id).andDeletedEqualTo(false);
        return UserPointMapper.selectOneByExampleSelective(example);
    }

    public LemonlaUserPoint findByUserId(Integer userid) {
        LemonlaUserPointExample example = new LemonlaUserPointExample();
        example.or().andUserIdEqualTo(userid).andDeletedEqualTo(false);
        return UserPointMapper.selectOneByExampleSelective(example);
    }

    public int add(LemonlaUserPoint UserPoint) {
        UserPoint.setAddTime(LocalDateTime.now());
        UserPoint.setUpdateTime(LocalDateTime.now());
        return UserPointMapper.insertSelective(UserPoint);
    }
    public int updateById(LemonlaUserPoint UserPoint) {
        UserPoint.setUpdateTime(LocalDateTime.now());
        return UserPointMapper.updateByPrimaryKeySelective(UserPoint);
    }


    public void pointForRegister(Integer userId) {
        LemonlaUserPoint userPoint = new LemonlaUserPoint();
        userPoint.setUserId(userId);
        userPoint.setPoint(1000L);
        add(userPoint);
    }

    public void consume(Integer userId, String content) {
        LemonlaUserPoint userPoint = findByUserId(userId);
        if (userPoint ==null) {
            pointForRegister(userId);
        }
        userPoint = findByUserId(userId);
        long tokens = 0l;
        if (!StringUtils.isEmpty(content)) {
            tokens = content.length();
        }
        long totalTokens = userPoint.getTokens()+tokens;
        long consumePoint = totalTokens /2 ;

        if (userPoint.getPoint() >= consumePoint) {
            userPoint.setPoint(userPoint.getPoint() - consumePoint);
        } else {
            userPoint.setPoint(0l);
        }
        updateById(userPoint);

    }
}
